package org.me;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Typeface;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.muc.InvitationRejectionListener;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.me.adapter.Adapter_Message;
import org.me.utils.Koneksi;
import org.me.utils.MyService;

public class Client extends Activity {
	
	ContactList contactList;
//	private PresenceSet sPresence;
//	private RemoveUser rUser;
//	private AddUser aUser;
	private XMPPConnection connection;
	Roster roster;
	static Handler mHandler = new Handler();
	private ArrayAdapter<String> mAdapter;
	private ArrayList<String> messages = new ArrayList<String>();
    private EditText mSendText;
    private ListView mList;
    private TextView rec;
    private TextView recStatus;
    ArrayList<String> as;
    ArrayList<String> gro;
    ArrayList<String> groups;
    Set<String> s;
    ArrayList<String> temp;
    ArrayList<ArrayList<String>> exContact;
    int gPos;
    int cPos;
    String chat;
    private Adapter_Message adapter;
    static String user;
    static Runnable message_run;
    ArrayList<String> mess1;
    String toRoster;
    String contactChat;
    String namaclient;
    LinearLayout layout;
    public static boolean isRoster = true;
	
	public static void setRoster(boolean isRoster) {
		Client.isRoster = isRoster;
	}

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        
        System.out.println("sssssssssssssssss");
        
        connection = Koneksi.getInstance().getConnection();
        roster = Koneksi.getInstance().getConnection().getRoster();
        
        System.out.println("wwwwwwwwwwwwwwwwwww");
        
        user = StringUtils.parseName(Koneksi.getInstance().getConnection().getUser());
        
        ContactList.mHandler.removeCallbacks(ContactList.Refresh);
        
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/tt0142m_.ttf");
        layout = (LinearLayout) findViewById(R.id.layoutinvite);
        
        mSendText = (EditText) this.findViewById(R.id.sendText);
        mList = (ListView) this.findViewById(R.id.listMessages);
        rec = (TextView) this.findViewById(R.id.rec);
        rec.setTypeface(font);
        
        System.out.println("qqqqqqqqqqqqq");
        
//        as = Koneksi.getInstance().getContact();
//        gro = Koneksi.getInstance().getContactGroup();
//        groups = Koneksi.getInstance().getAllGroup();
//        s = new LinkedHashSet<String>(groups);
//        temp = new ArrayList<String>(s);
//        Collections.sort(temp);
//        exContact = new ArrayList<ArrayList<String>>();
//        
//		for (int i=0; i<temp.size(); i++) {
//			exContact.add(new ArrayList<String>());
//		}
//		for (int i=0; i<temp.size(); i++) {
//			exContact.get(i).addAll(Koneksi.getInstance().getContactOneGroup(temp.get(i)));
//		}
//        gPos = Koneksi.getInstance().getGroupPosition();
//        cPos = Koneksi.getInstance().getChildPosition();
        
        contactChat = getIntent().getExtras().getString("userChat"); //name@address
        System.out.println("contactChat= "+contactChat);
        boolean broster = getIntent().getExtras().getBoolean("roster");
        System.out.println("roster= "+broster);
        System.out.println("isRoster= "+isRoster);
        final String type = getIntent().getExtras().getString("type");
        System.out.println("type= "+type);
        final String room = getIntent().getExtras().getString("room");
        final String password = getIntent().getExtras().getString("password");
        
        if (isRoster == false) {
        	System.out.println("aaaaaaaaaaa");
//			Intent tesintent = new Intent(Client.this, RequestRoster.class);
//			tesintent.putExtra("userRequest", contactChat);
//			startActivity(tesintent);
        	layout.setVisibility(View.VISIBLE);
        	
        	TextView textrequest = (TextView) findViewById(R.id.inviteroster);
    		textrequest.setTypeface(font);
    		if (type.equalsIgnoreCase("muc")) {
    			textrequest.setText("join to muc?");
			}
    		else {
    			textrequest.setText("add "+contactChat+" to your roster?");
    		}
    		System.out.println("bbbbbbbbbbbbbbbbbb");
            Button accept = (Button)findViewById(R.id.acceptroster);
            accept.setTypeface(font);
            accept.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				if (type.equalsIgnoreCase("muc")) {
    					MultiUserChat mMultiUserChat = new MultiUserChat(connection, room);
    					try {
    						if (password != null) {
    							mMultiUserChat.join(user, password);
    						} else {
    							mMultiUserChat.join(user);
    						}
    					} catch (XMPPException e) {
    					}
					}
    				else {
	    				Presence presence = new Presence(Type.subscribed);
	    				presence.setTo(contactChat);
	    				Koneksi.getInstance().getConnection().sendPacket(presence);
	    				
	    				try {
	    					roster.createEntry(contactChat, StringUtils.parseName(contactChat), new String[] {"Friends"});
	    				} catch (XMPPException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
    				}
    				layout.setVisibility(View.GONE);
    				setRoster(true);
    			}
    		});
            Button deny = (Button)findViewById(R.id.denyroster);
            deny.setTypeface(font);
            deny.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				if (type.equalsIgnoreCase("muc")) {
    					MultiUserChat.decline(Koneksi.getInstance().getConnection(), room, contactChat, "I'm busy");
					}
    				else {
	    				Presence presence = new Presence(Type.unsubscribe);
	    				presence.setTo(contactChat);
	    				Koneksi.getInstance().getConnection().sendPacket(presence);
    				}
    				layout.setVisibility(View.GONE);
    				setRoster(true);
    			}
    		});
		}        
        
        
//    	ArrayList<String> contacts = Koneksi.getInstance().getContactUser();
//    	System.out.println("123 "+roster.getEntry(contacts.get(0)).getName().toString());
    	//System.out.println("456 "+exContact.get(gPos).get(cPos));
//    	for (int i=0; i<contacts.size(); i++) {
//    		System.out.println("1 "+StringUtils.parseName(roster.getEntry(contacts.get(i)).getUser()));
//			if (roster.getEntry(contacts.get(i)).getUser().equalsIgnoreCase(contactChat)) {
//				System.out.println("2 "+roster.getEntry(contacts.get(i)).getName());
//				toRoster = roster.getEntry(contacts.get(i)).getName(); //nickname
//				rec.setText(toRoster);
//				System.out.println("3 "+toRoster);
//			}
//    	}
    	//System.out.println("toroster= "+toRoster);
        System.out.println("cccccccccccc");
    	int chatid = getIntent().getExtras().getInt("chatId");
//    	int mucid = getIntent().getExtras().getInt("mucId");
//      int presenceid = getIntent().getExtras().getInt("presenceId");
//      int mucid = getIntent().getExtras().getInt("mucId");
      NotificationManager man = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      man.cancel(chatid);
//      man.cancel(mucid);
//      man.cancel(presenceid);
//      man.cancel(mucid);
      MyService.messagenotif.remove(contactChat);
//      MyService.mucnotif.remove(contactChat);
      
      System.out.println("dddddddddddddd");
      
    	namaclient = StringUtils.parseName(contactChat); //name
    	rec.setText(namaclient);
        
        recStatus = (TextView) findViewById(R.id.recstatus);
        recStatus.setTypeface(font);
        if (Koneksi.getInstance().getOneStatus(contactChat) == "available") {
			recStatus.setText("Online");
		}
        else {
        	recStatus.setText("Offline");
        }
        
        System.out.println("eeeeeeeeeeeeeeeee");
//        if (Koneksi.getInstance().getOneStatus(exContact.get(gPos).get(cPos)) != null) {
//        	//System.out.println("####|statusclient: "+Koneksi.getInstance().getOneStatus(exContact.get(gPos).get(cPos)));
//		}
//        else {
//        	//System.out.println("####|statusclient: Offline Client");
//        }
        
        
//        mAdapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item, messages);
//        mAdapter.notifyDataSetChanged();
//        mList.setAdapter(mAdapter);


//        Koneksi.getInstance().receiveMessage();
//        //System.out.println("$$$$$$$$|mess: "+Koneksi.mess.size());
//        for (int i=0; i<Koneksi.mess.size(); i++) {
//        	mAdapter.add(Koneksi.mess.get(i));
//        	mAdapter.notifyDataSetChanged();
//		}

        ArrayList<String> rmv_index_mess = new ArrayList<String>();
        ArrayList<String> rmv_index_from = new ArrayList<String>();
        ArrayList<String> rmv_index_to = new ArrayList<String>();
        
        for (int i=0; i<Koneksi.getFrom().size(); i++) {
        	if ((Koneksi.getFrom().get(i).equalsIgnoreCase(namaclient) && Koneksi.getTo().get(i).equalsIgnoreCase(user)) || 
        			(Koneksi.getFrom().get(i).equalsIgnoreCase(user) && Koneksi.getTo().get(i).equalsIgnoreCase(namaclient))) {
    			//System.out.println("berhasil");
        		System.out.println("fffffffffffffffff");
        		messages.add(Koneksi.getMess().get(i));
//    			adapter.addItem(messages);
//    		    adapter.notifyDataSetChanged();
//    		    adapter.notifyDataSetInvalidated();
//    	    	mList.invalidateViews();
    			adapter = new Adapter_Message(getBaseContext(), messages, user);
    			mList.setAdapter(adapter);
    			rmv_index_mess.add(Koneksi.getMess().get(i));
    			rmv_index_from.add(Koneksi.getFrom().get(i));
    			rmv_index_to.add(Koneksi.getTo().get(i));
    		}
		}
//        Koneksi.mess.removeAll(rmv_index_mess);
//        Koneksi.from.removeAll(rmv_index_from);
        
//        adapter = new Adapter_Message(getBaseContext(), messages, user);
//		mList.setAdapter(adapter);
        
//        message_run = new Runnable() {
//			@Override
//			public void run() {
////				mess1 = Koneksi.mess;
////				//System.out.println("@@@@@@@|message size: "+messages.size());
////				//System.out.println("@@@@@@@|koneksi size: "+Koneksi.mess.size());
////				//System.out.println("@@@@@@@|mess1 size: "+mess1.size());
////				if (mess1.size() != messages.size()) {
////					messages.clear();
////					messages.addAll(mess1);
////				}
////				adapter.addItem(messages);
////				
////				adapter.notifyDataSetChanged();
////		    	adapter.notifyDataSetInvalidated();
////		    	mList.invalidateViews();
////		    	
////		    	//System.out.println("+++++++|message_run delay|++++++");
////		    	mHandler.postDelayed(message_run, 2000);
//				// TODO Auto-generated method stub
//				mHandler.postDelayed(this, 10);
//				adapter = new Adapter_Message(getBaseContext(), messages, user);
//				mList.setAdapter(adapter);
//				//System.out.println("+++++++|message_run delay|++++++");
//			}
//		};
//		mHandler.post(message_run);
		
//        adapter = new Adapter_Message(getBaseContext(), messages, 1);
//		mList.setAdapter(adapter);
//        //System.out.println("$$$$$$|koneksi mess: "+Koneksi.mess);
//        //System.out.println("$$$$$$|koneksi from: "+Koneksi.from);
//        //System.out.println("$$$$$$|koneksi to: "+Koneksi.to);
		
        if (connection != null) {
		    PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
		    connection.addPacketListener(new PacketListener() {
		        public void processPacket(Packet packet) {
		        	//System.out.println("berhasil2");
		            Message message = (Message) packet;
		            if (message.getBody() != null) {
		            	//System.out.println("berhasil3");
		                String fromName = StringUtils.parseName(message.getFrom());
		                String toName = StringUtils.parseName(message.getTo());
		                //System.out.println("fromName= "+fromName+"||||||toRoster= "+toRoster+"||||||exContact= "+exContact.get(gPos).get(cPos));
		                if (fromName.equalsIgnoreCase(namaclient)) {
		                	messages.add(fromName + ": " + message.getBody());
		                	
//		                	adapter.addItem(messages);
//		        		    adapter.notifyDataSetChanged();
//		        		    adapter.notifyDataSetInvalidated();
//		        	    	mList.invalidateViews();
			                mHandler.post(new Runnable() {
			                    public void run() {
//			                    	//System.out.println("++++++|dalem run|+++++++++");
			                    	adapter = new Adapter_Message(getBaseContext(), messages, user);
				            		mList.setAdapter(adapter);
			                    }
			                });
						}
		            }
		        }
		    }, filter);
		}
        
        Button send = (Button) this.findViewById(R.id.send);
        send.setTypeface(font);
        send.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	String to = namaclient;
                String text = mSendText.getText().toString();

                if(!text.equalsIgnoreCase("")) {
                	Koneksi.getInstance().sendMessage(to, text);
//                	mAdapter.add(StringUtils.parseName(connection.getUser()) + ": " + text);
//                	mAdapter.notifyDataSetChanged();
                	messages.add(StringUtils.parseName(connection.getUser()) + ": " + text);
                	
                	Koneksi.getMess().add(StringUtils.parseName(connection.getUser()) + ": " + text);
                	Koneksi.getFrom().add(StringUtils.parseName(connection.getUser()));
                	Koneksi.getTo().add(to);
                	
                	adapter = new Adapter_Message(getBaseContext(), messages, user);
            		mList.setAdapter(adapter);
//                	adapter.addItem(messages);
//        		    adapter.notifyDataSetChanged();
//        		    adapter.notifyDataSetInvalidated();
//        	    	mList.invalidateViews();
//                	adapter = new Adapter_Message(getBaseContext(), messages, 0);
//					mList.setAdapter(adapter);
                }
                mSendText.setText("");
            }
        });
        
    }
    
//    public void update(ArrayList<String> message) {
//    	adapter.addItem(messages);
//	    adapter.notifyDataSetChanged();
//	    adapter.notifyDataSetInvalidated();
//    	mList.invalidateViews();
//	}
//    
//    @Override
//	protected void onResume() {
//		// TODO Auto-generated method stub
//		adapter.notifyDataSetChanged();
//    	adapter.notifyDataSetInvalidated();
//    	mList.invalidateViews();
//		super.onResume();
//	}

    @Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
    	mHandler.removeCallbacks(message_run);
		ContactList.mHandler.post(ContactList.Refresh);
		super.onBackPressed();
	}
    
//    @Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		// TODO Auto-generated method stub
//    	if (keyCode == KeyEvent.KEYCODE_BACK) {
//            mHandler.removeCallbacks(message_run);
//        }
//		return super.onKeyDown(keyCode, event);
//	}


//	public boolean onCreateOptionsMenu(Menu menu) {
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.menu_client, menu);
//        return true;
//    }
//    public boolean onOptionsItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//			case R.id.presence :
//				sPresence = new PresenceSet(this);
//				sPresence.show();
//				sPresence.setTitle("Set Presence");
//				break;
//			case R.id.rmvUser :
//				rUser = new RemoveUser(this);
//				rUser.show();
//				rUser.setTitle("Remove User");
//				break;
//			case R.id.addUser :
//				aUser = new AddUser(this);
//				aUser.show();
//				aUser.setTitle("Add User");
//				break;
//			default :
//				
//		}
//        return true;
//    }
	    
}